package com.streaminggbs.common.utils;


import com.google.common.collect.Maps;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

public final class DateUtil {

	// Grace style
	public static final String PATTERN_GRACE = "yyyy/MM/dd HH:mm:ss";
	public static final String PATTERN_GRACE_NORMAL = "yyyy/MM/dd HH:mm";
	public static final String PATTERN_GRACE_SIMPLE = "yyyy/MM/dd";

	// Classical style
	public static final String PATTERN_CLASSICAL = "yyyy-MM-dd HH:mm:ss";
	public static final String PATTERN_CLASSICAL_NORMAL = "yyyy-MM-dd HH:mm";
	public static final String PATTERN_CLASSICAL_SIMPLE = "yyyy-MM-dd";
	public static final String TWELVE = "yyMMddHHmmss";
	public static final String TDATE = "yyyy-MM-dd'T'hh:mm:ss";

	public static String formatDate(Date src, String formatPattern) {
		if (src==null){return "";}
		DateFormat fmt = new SimpleDateFormat(formatPattern);
		return fmt.format(src);
	}

	public static String formatDate(Date src) {
		return formatDate(src, "yyyy-MM-dd HH:mm:ss");
	}

	public static String formatDate() {
		return formatDate(new Date(), "yyyy-MM-dd");
	}

	public static String formatDate(String formatPattern) {
		return formatDate(new Date(), formatPattern);
	}

	public static Date getDate() {
		Calendar calendar = Calendar.getInstance();
		return calendar.getTime();
	}

	/**
	 * 获取当前时间 yyyyMMddHHmmss
	 * @return String
	 */
	public static String getNumDate() {
		Date now = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String s = outFormat.format(now);
		return s;
	}

	/**
	 * 根据指定格式将指定字符串解析成日期
	 *
	 * @param str
	 *            指定日期
	 * @param pattern
	 *            指定格式
	 * @return 返回解析后的日期
	 */
	public static Date parse(String str, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			return sdf.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 比较两个Date类型的日期大小
	 *
	 * @param sDate开始时间
	 *
	 * @param eDate结束时间
	 *
	 * @return result返回结果(0--相同 1--前者大 2--后者大)
	 * */
	public static int compareDate(Date sDate, Date eDate) {
		int result = 0;
		// 将开始时间赋给日历实例
		Calendar sC = Calendar.getInstance();
		sC.setTime(sDate);
		// 将结束时间赋给日历实例
		Calendar eC = Calendar.getInstance();
		eC.setTime(eDate);
		// 比较
		result = sC.compareTo(eC);
		// 返回结果
		return result;
	}
	public static int getIntTime(){
		Long t = System.currentTimeMillis() / 1000;
		return t.intValue();
	}

	/**
	 * 是不否为今天
	 * @param second  utc转换忧的秒
	 * @return
	 */
	public static boolean isToday(int second) {
		Calendar today = Calendar.getInstance();
		Calendar compareday = Calendar.getInstance();
		compareday.setTimeInMillis(second * 1000L);

		if (today.get(Calendar.YEAR) == compareday.get(Calendar.YEAR)
				&& today.get(Calendar.DAY_OF_MONTH) == compareday.get(Calendar.DAY_OF_MONTH)) {
			return true;
		}

		return false;

	}
	/**
	 * 获取下一天0分0秒
	 * @return
	 */
	public static Date nextToday() {
		Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DAY_OF_MONTH, 1);
		return cal.getTime();
	}
	/**
	 * 获取下一天0分0秒
	 * @return
	 */
	public static Date reduceDate(int days) {
		Date beginDate = new Date();
		Calendar date = Calendar.getInstance();
		date.setTime(beginDate);
		date.set(Calendar.DATE, date.get(Calendar.DATE) - days);
		return date.getTime();
	}

	 /**
     * 返回指定日期的起始时间
     *
     * @param date
     *            指定日期（例如2014-08-01）
     * @return 返回起始时间（例如2014-08-01 00:00:00）
     */
    public static Date getIntegralStartTime(Date date) {
        return getResetTime(date, 0, 0, 0);
    }
    /**
     * 获取重置指定日期的时分秒后的时间
     *
     * @param date
     *            指定日期
     * @param hour
     *            指定小时
     * @param minute
     *            指定分钟
     * @param second
     *            指定秒
     * @return 返回重置时分秒后的时间
     */
    public static Date getResetTime(Date date, int hour, int minute, int second) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.set(Calendar.HOUR_OF_DAY, hour);
        cal.set(Calendar.SECOND, minute);
        cal.set(Calendar.MINUTE, second);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

	/**
	 * 当前时间点增加小时数量
	 * @param date
	 * @param hour
	 * @return
	 */
	public static Date addHour(Date date, int hour){
  		Calendar cal = Calendar.getInstance();
  		cal.setTime(date);
		cal.add(Calendar.HOUR, hour);
  		return cal.getTime();
  	}

    //日期往后多少分钟
  	public static Date addMinute(String strDate, int minute){
  		Calendar cal = Calendar.getInstance();
  		SimpleDateFormat sFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  		cal.setTime(sFmt.parse( (strDate), new ParsePosition(0)));

  		if (minute != 0) {
  			cal.add(cal.MINUTE,minute);
  		}
  		return cal.getTime();
  	}
	//日期往后多少秒
	public static Date addSecond(String strDate, int second){
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		cal.setTime(sFmt.parse( (strDate), new ParsePosition(0)));

		if (second != 0) {
			cal.add(cal.SECOND,second);
		}
		return cal.getTime();
	}
	/**
	 * 添加分钟
	 * @param date
	 * @param minute
	 * @return
	 */
	public static Date addMinute(Date date, int minute){
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		cal.setTime(date);
		if (minute != 0) {
			cal.add(cal.MINUTE,minute);
		}
		return cal.getTime();
	}

  	/**
  	 * 判断当前时间是否在时间间隔内
  	 * @param sDate
  	 * @param eDate
  	 * @return
  	 */
  	public static boolean isIntervalTime(Date sDate, Date eDate) {
  		Date now = new Date();
  		boolean f1 = compareDate(sDate,now) <= 0;
  		boolean f2 = compareDate(eDate,now) >= 0;
		if(f1 && f2) {
			return true;
		} else {
			return false;
		}
	}

  	/**
  	 * 日期转字符串
  	 * @param date
  	 * @param formatStr
  	 * @return
  	 */
  	public static String dateToString(Date date, String formatStr) {
        DateFormat format = new SimpleDateFormat(formatStr);
        return format.format(date);
    }

  	/**
  	 * 字符串转ymd
  	 * @param str
  	 * @return
  	 */
    public static String stringToYmd(String str) {
        return str.substring(0, 10).replace("-", "") ;
    }


  	/**
  	 * 字符串转日期
  	 * @param str
  	 * @return
  	 */
    public static Date stringToDate(String str) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

  	/**
  	 * 字符串转日期
  	 * @param str
  	 * @return
  	 */
    public static Date stringToDateYMD(String str) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
  	 * 数字字符串转日期
  	 * @param str
  	 * @return
  	 */
    public static Date numStringToDate(String str) {
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 获取当前时间，不带横线
	 * @return
	 */
	public static String getNowDate() {
		String systemdate = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
		return systemdate;
	}

	/**
	 * 获取当前时间
	 * @return
	 */
	public static String getSqlDateStr() {
		String systemdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
		return systemdate;
	}

	/**
	 * 获取当前时间
	 * @return
	 */
	public static String getFourDate() {
		String ymd = getYmd();
		return ymd.substring(4,ymd.length());
	}

	/**
	 * 获取当前时间
	 * @return
	 */
	public static String getYmd() {
		String systemdate = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
		return systemdate;
	}

	/**
	 * 产生4位随机数
	 */
	public static String getFourRandom(){
		int random1 = (int) (Math.random() * 9000 + 1000);
		String random = String.valueOf(random1);
		return random;
	}

	/**
	 * 计算两个日期之间相差的天数
	 *
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static final int daysBetween(Date date1, Date date2) {

		Calendar time1 = Calendar.getInstance();
		Calendar time2 = Calendar.getInstance();
		time1.setTime(date1);
		time2.setTime(date2);
		int days = 0;
		if(time1.getTime().getTime() >= time2.getTime().getTime()){
			days = ((int) (time1.getTime().getTime() / 1000) - (int) (time2.getTime().getTime() / 1000)) / 3600 / 24;
		}else{
			days = ((int) (time2.getTime().getTime() / 1000) - (int) (time1.getTime().getTime() / 1000)) / 3600 / 24;
		}
		return days;
	}

	/**
     * 计算两个日期之间相差的天数
     * @return 相差天数
     * @throws ParseException
     */
    public static int diffDayBetween(Date smdate, Date bdate){
    	try{
	    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	        smdate=sdf.parse(sdf.format(smdate));
	        bdate=sdf.parse(sdf.format(bdate));
	        Calendar cal = Calendar.getInstance();
	        cal.setTime(smdate);
	        long time1 = cal.getTimeInMillis();
	        cal.setTime(bdate);
	        long time2 = cal.getTimeInMillis();

	        long between_days= 0;
	        if(time1 > time2){
	        	between_days=(time1-time2)/(1000*3600*24);
			}else{
				between_days=(time2-time1)/(1000*3600*24);
			}
	        return Integer.parseInt(String.valueOf(between_days));
    	}catch(Exception e){
    		return 0;
    	}

    }

    /**
	 * 计算两个日期之间相差秒
	 *
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static final int secBetween(String sdate1, String sdate2) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date1 = null;
		try {
			date1 = df.parse(sdate1);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Date date2 = null;
		try {
			date2 = df.parse(sdate2);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Calendar time1 = Calendar.getInstance();
		Calendar time2 = Calendar.getInstance();
		time1.setTime(date1);
		time2.setTime(date2);

		int sec = 0;
		if(time1.getTime().getTime() >= time2.getTime().getTime()){
			sec = ((int) (time1.getTime().getTime() / 1000) - (int) (time2.getTime().getTime() / 1000));
		}else{
			sec = ((int) (time2.getTime().getTime() / 1000) - (int) (time1.getTime().getTime() / 1000));
		}
		return sec;
	}

	/**
	 * 获取插入数据库格式的时间
	 * @return
	 */
	public static String getSQLDate() {
		String systemdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(Calendar.getInstance().getTime()); // 获取系统当前时间
		return systemdate;
	}

	/**
	 * 和当前时间差
	 * @param date
	 * @return 当前时间 - 返回小时
	 */
	public static int currentTimeDiffToHour(String date) {
		if(date == null || date.equals("")){
			return 25;
		}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Long longss = System.currentTimeMillis() -  df.parse(date).getTime();
			int hour = Integer.parseInt(longss/(1000*3600)+"");
			return hour;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 25;
	}
	/**
	 * 计算时间字串对应的时间戳
	 * @param timeStr
	 * @return 时间戳
	 */
	public static Long getTimestamp(String timeStr) {
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = format.parse(timeStr);
			Long timestamp = date.getTime();
			return timestamp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 判断两个时间字符串之差
	 * @param date1
	 * @param date2
	 * @return 毫秒数
	 */
	public static Long dateDiff(Date date1, Date date2) {
		return date1.getTime() - date2.getTime();
	}

	//日期往后多少天
	public static Date addDate(String strDate, int day){
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		cal.setTime(sFmt.parse( (strDate), new ParsePosition(0)));

		if (day != 0) {
			cal.add(cal.DATE,day);
		}
		return cal.getTime();
	}

	/**
	 * 获取间隔八个小时的日期值
	 * @param startDate
	 * @param endDate
	 * @param list
	 */
	public static void getIntervalDate(Date startDate, Date endDate, List<Map<String, Date>> list) {
		long differHours = (endDate.getTime()-startDate.getTime())/ 1000 / 3600;
		if (differHours > 8) {
			Date newEndDate = DateUtil.addHour(startDate,8);
			Map<String, Date> map = Maps.newHashMap();
			map.put("startDate",startDate);
			map.put("endDate",newEndDate);
			list.add(map);
			getIntervalDate(newEndDate,endDate,list);
		} else {
			Map<String, Date> map = Maps.newHashMap();
			map.put("startDate",startDate);
			map.put("endDate",endDate);
			list.add(map);
		}
	}
	//根据日期取得星期几
	public static int getWeek(Date date) {
		int[] weeks = {7, 1, 2, 3, 4, 5, 6};
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (week_index < 0) {
			week_index = 0;
		}
		return weeks[week_index];
	}
	public static void main(String[] args) throws Exception {

	}


}
